<?php
/**
 * Created by PhpStorm.
 * User: Auser
 * Date: 2017/5/23
 * Time: 13:12
 */

namespace App\Services\Echarts;
use WechatUserService;
use UserRecordService;
use TestingConfig;
use ParamConfig;
use AdminEvaluateService;
use App\Helper\Tool;
use App\Admin\Controllers\DecreaseWeightController;
use Illuminate\Support\Facades\DB;
use Encore\Admin\Facades\Admin;
use App\Services\IdEncryptService;
use SendTplUserService;
use UserRemarkService;
use DecreaseSelectHelper;
use JzMatchRelationService;
class DecreaseUserInfoHelper
{
    protected $tag = 'DW.userInfo';


    public function allData($tid,$appid){

    }

    /**用户详情
     * @param $id recorde表id
     * @return mixed
     */
    public function userInfo($id,$tid,$time){
        $record = $this->getRecode($id);
        $basedata = $this->base_user_data($record['uid']);
        $heading = TestingConfig::getValue('wechat.user.heading.path');
        $headImgUrl = $heading.$basedata['headimgurl'];
        $headImgUrl = str_replace("min","max",$headImgUrl);
        $nickName = $record['nick_name'];
        $title= $record['testing_name'];
        $special = $this->formateData($record['final_answers'],17,"answer");
        $sendTplFrom = $this->startSendTpl($record['uid'],$record['from_appid'],$tid,$id,$time);
        $base_url = TestingConfig::getValue('website_url');
        $timeline = $base_url."/admin/testing/decrease/users/timeline/".$record['uid'];
        $remark = $this->remark($id,$record['uid'],$tid,$record['from_appid'],$time);
        $content =ParamConfig::getValue("DW.admin.user.info.content");
        $content = str_replace(["HEADURL","USER","TITLE","SPECIL",'FROM','ADDREMARK','REMARK'],[$headImgUrl,$nickName,$title,$special,$sendTplFrom,$remark['url'],$remark['note']],$content);
        return $content;
    }

    /**用户信息备注
     * @param $rid
     * @param $uid
     * @param $tid
     * @return mixed
     */
    public function remark($rid,$uid,$tid,$appid,$time){
        $base_url = TestingConfig::getValue('website_url');
        $data = UserRemarkService::checkRemark($rid,$uid,$tid);
        if($data){//存在备注
            $res['note'] = $data['remark'];
        }else{//不存在备注
            $res['note'] =  "";
        }
        $res['url'] = $base_url."/admin/testing/decrease/users/remark"."?rid=".$rid."&uid=".$uid."&tid=".$tid."&appid=".$appid."&time=".$time;
        return $res;
    }

    /**判断用户是否有备注信息
     * @param $rid
     * @param $uid
     * @param $tid
     * @return mixed
     */
    public function remarkData($rid,$uid,$tid,$appid,$time){
        $base_url = TestingConfig::getValue('website_url');
        $data = UserRemarkService::checkRemark($rid,$uid,$tid);
        $res['tid'] = $tid;
        $res['rid'] = $rid;
        $res['uid'] = $uid;
        //$res['url'] =  $base_url."/admin/testing/decrease/user/info/".$rid."/".$tid."/".base64_encode($appid)."/".$time;
        $res['url'] = $base_url."/admin/testing/decrease/user/info/".$rid."/".$uid."/".$tid."/".base64_encode($appid)."/".$time;

        if($data){
            $res['remark'] = $data['remark'];
        }else{
            $res['remark'] = "";
        }
        return $res;
    }

    public function storeRemark($data){
       return UserRemarkService::Remark($data);
    }


    //手动开始和结束用户发送模板消息from
    public function startSendTpl($uid,$appid,$tid,$id,$time){
        $user = SendTplUserService::checkUser($uid,$appid,$tid);
        $base_url = TestingConfig::getValue('website_url');
       // $url = $base_url."/admin/testing/decrease/user/info/".$id."/".$tid."/".base64_encode($appid)."/".$time;
         $url = $base_url."/admin/testing/decrease/user/info/".$id."/".$uid."/".$tid."/".base64_encode($appid)."/".$time;
        if($user && $user['is_start'] == 1){//显示结束推送按钮
            $from = ParamConfig::getValue("DW.admin.user.endsendtpl.from");
            $origin = ['#ACTION','#UID','#TID','#APPID','#URL'];
            $action =$base_url .'/api/testing/wechat/admin/endsendtpl';
            $from = str_replace($origin,[$action,$uid,$tid,$appid,base64_encode($url)],$from);
        }else{//显示开始推送按钮
            $from =  ParamConfig::getValue("DW.admin.user.startsendtpl.from");
            $origin = ['#ACTION','#UID','#TID','#APPID','#URL'];
            $action = $base_url.'/api/testing/wechat/admin/startsendtpl';
            $from = str_replace($origin,[$action,$uid,$tid,$appid,base64_encode($url)],$from);
        }
        return $from;
    }

    /**答题记录
     * @param $id
     * @return array
     */
    public function recode($id,$tid){
        $record = $this->getRecode($id);
        $height = $this->formateData($record['final_answers'],1,"answer");
        $weight = $this->formateData($record['final_answers'],2,"answer");
        $goal = $this->formateData($record['final_answers'],19,"answer");
        $habit = $this->formateData($record['final_answers'],7,"answer");
        $content ='身高：&nbsp;&nbsp;&nbsp;'.$height.' &nbsp;&nbsp;(cm)'.'&nbsp;&nbsp;&nbsp;体重：&nbsp;&nbsp;&nbsp;'.$weight.' &nbsp;&nbsp;(kg)'.'&nbsp;&nbsp;&nbsp;减重目标：&nbsp;&nbsp;&nbsp;'.$goal.' &nbsp;&nbsp;(kg)</br>'.'饮食习惯：&nbsp;&nbsp;&nbsp;'.$habit;
        $base_url = TestingConfig::getValue('website_url');
        $infourl = $base_url."/admin/testing/decrease/info/".$id."/".$tid;
        $html = '<div class="small-box bg-aqua"><div style="height: 120px"  class="inner"><h3></h3><p>'.$content.'</p></div><div class="icon"><i class="fa fa-book"></i></div><a href="'.$infourl.'" class="small-box-footer">更多<i class="fa fa-arrow-circle-right"></i></a></div>';
        $data=array(
            'time'=> $record['created_at'],
            'html'=>$html
        );
        return $data;
    }

    /**中间值及减肥方案
     * @param $id
     *
     */
    public function middle($id,$tid){
        $record = $this->getRecode($id);
        $obj = new  DecreaseWeightController;
        $res = $obj->formatConclusionOne($record);
        $base_url = TestingConfig::getValue('website_url');
        $content = $res[4]."</br>".$res[5]."</br>".$res[6]."</br>".$res[7]."";
        $infourl = $base_url."/admin/testing/decrease/middleinfo/".$id."/".$tid;
        $html = '<div class="small-box bg-aqua"><div style="height: 120px"  class="inner"><h3></h3><p>'.$content.'</p></div><div class="icon"><i class="fa fa-book"></i></div><a href="'.$infourl.'" class="small-box-footer">更多<i class="fa fa-arrow-circle-right"></i></a></div>';
        $data=array(
            'time'=> $record['created_at'],
            'html'=>$html
        );
        return $data;
    }

    /**调打卡接口获取用户具体打卡数据
     * @param $id  测评结果id
     * @param $time
     * @return mixed
     */
    public function baseUserCircleData($id,$time){
        $record = $this->getRecode($id);
        $uid = $record['uid'];
        //$uid = 34253;
        //调用问答接口
        $wenda_base_url = TestingConfig::getValue('wenda.base.url');
        $wenda_url = $wenda_base_url."/circle/ajax/get_defating_user_punch_status/uid-".$uid."&time=".$time;
        $wenda = json_decode(curlRequest($wenda_url),true);
        //打卡数据
        $crileData = $wenda['rsm'];
        return $crileData;
    }

    /**用户打卡信息及评价信息
     * @param $id
     * @param $tid
     * @param $time
     * @param $appid
     * @param $crileData
     * @return mixed
     */
    public function userCircle($id,$tid,$time,$appid,$crileData){
        $record = $this->getRecode($id);
        $uid = $record['uid'];
        $data['imgSportArr'] = [];
        $data['imgFoodArr'] = [];
        if($crileData) {//存在打卡
            $sportArr = [];
            if (isset($crileData['sports'])) {//已运动打卡
                $sport = $crileData['sports'];
                foreach ($sport as $k => $v) {
                    $sportArr['description'] = $v['detail_content'];
                    $sportArr['time'] = date("Y-m-d H:i:s", $v['add_time']);
                    $attch_sport = [];
                    $imgArr_sport = [];
                    foreach ($v['attachs'] as $key => $value) {
                        $attch_sport['attachs_id'] = $key;
                        $attch_sport['imgsrc'] = $value['attachment'];
                        array_push($imgArr_sport, $attch_sport);
                    }
                    $sportArr['img'] = $imgArr_sport;
                    array_push($data['imgSportArr'], $sportArr);
                }
            }
            $foodArr = [];
            if (isset($crileData['diets'])) {//饮食打卡
                    $food = $crileData['diets'];
                    foreach($food as $k => $v){
                        $foodArr['description']=$v['detail_content'];
                        $foodArr['time']=date("Y-m-d H:i:s",$v['add_time']);
                        $attch_food = [];
                        $imgArr_food = [];
                        foreach($v['attachs'] as $key => $value){
                            $attch_food['attachs_id']="img".$key;
                            $attch_food['imgsrc']=$value['attachment'];
                            array_push($imgArr_food,$attch_food);
                        }
                        $foodArr['img']=$imgArr_food;
                        array_push( $data['imgFoodArr'],$foodArr);
                    }
            }
        }
        //打卡评价
        $evaluateService = AdminEvaluateService::getEid($uid,$time);
        if($evaluateService['eid']){
             $result = ParamConfig::getById($evaluateService['eid']);
             $evaluate =$result['value'];
        }else{
            $evaluate = $evaluateService['custom'];
        }
        //时间请求地址
        $base_url = TestingConfig::getValue('website_url');
        //$data['url'] = $base_url."/admin/testing/decrease/user/info/".$id."/".$tid."/".base64_encode($appid);
        $data['url'] = $base_url."/admin/testing/decrease/user/info/".$id."/".$uid."/".$tid."/".base64_encode($appid);
        $data['sport'] = "<span style='font-size: 16px'>运动打卡情况：</span>";
        $data['food'] = "<span style='font-size: 16px'>饮食打卡情况：</span>" ;
        $data['evaluate'] = "<span style='font-size: 16px'>打卡评价：</span><span style='font-size: 14px; padding: 6px 20px;'>".$evaluate."</span>" ;
        return $data;
    }



    /**用户打卡评价
     * @param $id
     * @param $tid
     * @param $time
     * @return string
     */
    public function evaluate($id,$tid,$time,$appid,$baseCircleData){
        $optionArr = ParamConfig::getByTag('DW.admin.evaluate');
        $base_url = TestingConfig::getValue('website_url');
        $record = $this->getRecode($id);
        $adminUser = Admin::user()->name;
        $detailId = isset($baseCircleData['diets']) ? $baseCircleData['diets'][0]['detail_id'] : "";
        $url = $base_url."/api/testing/wechat/admin/evaluate";
        $option = '<div class="box-body"><input type="hidden" name="_token" value="{{ csrf_token() }}"><input type="hidden" name="uid" value="'.$record['uid'].'"><input type="hidden" name="id" value="'.$id.'"><input type="hidden" name="tid" value="'.$tid.'"><input type="hidden" name="time" value="'.$time.'"><input type="hidden" name="appid" value="'.$appid.'"><input type="hidden" name="admin" value="'.$adminUser.'"><input type="hidden" name="detailid" value="'.$detailId.'">';
        foreach($optionArr as $k => $v){
           $option.='<label><input onclick="$('."'#custom_id'".').addClass('."'hidden'".')" name="eid"  type="radio" value="'.$v['id'].'"/>'.$v['value'].'</label></br>';
        }
        $option.='<label><input onclick="$('."'#custom_id'".').removeClass('."'hidden'".')" name="eid" type="radio" value="" >自定义评价：</label></br><label class="hidden" id="custom_id" ><textarea name="custom" Cols="150" Rows="4" placeholde="请输入..."></textarea></label></br>';
        $content = '<form action="'.$url.'" method="post">'. $option.'<div class="col-sm-4"><div class="btn-group pull-right"><button type="submit" class="btn btn-info">确认</button></div></div></form></div> ';
        return $content;
    }

    /**
     * @param $appid
     * @param $time 0000-00-00
     */
    public function stats($appid,$time){
        $stats = $this->baseStats($appid,$time);
        $all_num = count($stats['users']);
        $food_num=0;
        $sport_num=0;
        if($stats['food']){
            $food_num=count(array_unique($stats['food']));
        }
        if($stats['sport']){
            $sport_num=count(array_unique($stats['sport']));
        }
        $base_url = TestingConfig::getValue('website_url');
        $data['all_num'] = $all_num;
        $data['food_num'] = [$food_num,$all_num-$food_num];
        $data['sport_num'] = [$sport_num,$all_num-$sport_num];
        $data['posturl'] =$base_url."/admin/testing/decrease/user/stats/".base64_encode($appid);
        $data['food_moreurl'] = $base_url."/admin/testing/decrease/users/".base64_encode($appid)."/food/".$time;
        $data['sport_moreurl'] = $base_url."/admin/testing/decrease/users/".base64_encode($appid)."/sport/".$time;
        return $data;
    }

    /**用户打卡统计详情
     * @param $appid
     * @param $type
     * @param $time
     * @return mixed
     */
    public function statsInfo($appid,$type,$time){
        $stats = $this->baseStats($appid,$time);
        if($type == "food"){
            $have_food_id = $stats['food'];
            $haveNot_food_id = array_diff($stats['users_id'],$have_food_id);
            $data['have_food']=$this->getNameByuid($have_food_id,$stats['users']);
            $data['haveNot_food']=$this->getNameByuid($haveNot_food_id,$stats['users']);
        }
        if($type == "sport"){
            $have_sport_id = $stats['sport'];
            $haveNot_sport_id = array_diff($stats['users_id'],$have_sport_id);
            $data['have_sport']=$this->getNameByuid($have_sport_id,$stats['users']);
            $data['haveNot_sport']=$this->getNameByuid($haveNot_sport_id,$stats['users']);
        }
        return $data;
    }

    /**根据uid获取用户name
     * @param $idArr
     * @param $dataArr
     * @return array
     */
    protected function getNameByuid($idArr,$dataArr){
        $name = array();
        foreach($idArr as $k => $v){
            foreach($dataArr as $key => $value){
                if($v == $value['uid']){
                    $name[$k][0]=$k;
                    $name[$k][1]=$value['user_name'];
                }
            }
        }

        return $name;
    }

    /***返回打卡统计的uid(总uid,饮食uid,运动uid)数组
     * @param $appid
     * @param $time
     * @return array
     */
    public function baseStats($appid,$time){
        $data = [];
        $wenda = DB::connection('wenda');
        $users = $wenda->table("qz_users")->select("uid","user_name")->where("from_appid",$appid)->get();
        $data['users']= json_decode(json_encode($users),true);
        $data['users_id'] = array_column($data['users'], 'uid');
        $starttime = strtotime($time." 00:00:00");
        $endtime =  strtotime($time." 23:59:59");
        $food = $wenda->table('qz_circle_detail')->where('circle_id',11)->whereBetween('add_time',[$starttime,$endtime])->where('action_type',"punch") ->whereIn('published_id',$data['users_id'])->pluck('published_id')->toarray();
        $sport = $wenda->table('qz_circle_detail')->where('circle_id',12)->whereBetween('add_time',[$starttime,$endtime])->where('action_type',"punch") ->whereIn('published_id',$data['users_id'])->pluck('published_id')->toarray();
        $data['food'] = array_unique($food);
        $data['sport'] =array_unique($sport);
        return $data;
    }



    /**根据测评答案id获取信息
     * @param $id
     * @return mixed
     */
    public function getRecode($id){
       return UserRecordService::getById($id);
    }

    /**根据json字符串返回答案数组
     * @param $answer
     * @return array
     */
    protected function formateData($answer_json,$index,$type="answer"){
        $answer = Tool::strToArr($answer_json);
        foreach($answer as $key => $value){
            if($value['index'] == $index){
                switch ($type){
                    case "answer":
                        $res = $answer[$key]['answer'];
                        break;
                    case "weight":
                        $res = $answer[$key]['weight'];
                }
            }
        }
        return $res;
    }

    /**根据用户id获取用户表信息
     * @param $uid
     * @return mixed
     */
    protected function base_user_data($uid){
        $user_data = WechatUserService::getByUid($uid);
        return $user_data;
    }

    /**根据uidtid匹配用户
     * @param $uid
     * @param $tid
     * @return mixed
     */
    public function matchStauts($uid,$tid){
      return  JzMatchRelationService:: matchByUidTid($uid,$tid);
    }


}